import Option.iVix
import datetime
import pandas as pd
import Core.Gadget as Gadget
from SystematicFactors.General import *


def Auto_Calc_iVix(database, datetime2):
    datetime1 = Find_Last_Update_Date(database, "iViX_50ETF")
    Calc_iVix(database, datetime1, datetime2)


def Calc_iVix(database, datetime1, datetime2):
    #
    # datetime1 = datetime.datetime(2015, 2, 1)
    underly_symbol = "510050.SH"

    # 防止过慢，逐月计算
    tmp_datetime1 = datetime1 - datetime.timedelta(days=30)
    tmp_datetime2 = datetime2 + datetime.timedelta(days=30)
    time_ranges = Gadget.GenerateTimeRange_Monthly(tmp_datetime1, tmp_datetime2)
    for time_range in time_ranges:
        begin_date = time_range[0]
        end_date = time_range[1]
        #
        df_result = Option.iVix.Calc_VIX_Database(database, begin_date, end_date, underly_symbol)
        print(df_result)
        df_result["date"] = df_result["DATADATE"]
        #
        Save_Systematic_Factor_To_Database(database, df_result, save_name="iViX_50ETF", field_name="VIX")
    #
    tmp_datetime1 = datetime1 - datetime.timedelta(days=30)
    df_vix = Load_Systematic_Factor(database, "iViX_50ETF", datetime1=tmp_datetime1, datetime2=datetime2, indexed=True)
    df_weekly = df_vix.resample("W").last()
    df_weekly["Dif"] = df_weekly['iViX_50ETF'].map(np.log).diff()
    df_weekly = df_weekly[1:]
    df_weekly.dropna(inplace=True)
    #
    Save_Systematic_Factor_To_Database(database, df_weekly, save_name="iViX_50ETF_Weekly_Dif", field_name="Dif")


if __name__ == '__main__':
    #
    from Core.Config import *
    pathfilename = os.getcwd() + "\..\Config\config2.json"
    config = Config(pathfilename)
    database = config.DataBase("JDMySQL")
    realtime = config.RealTime()
    #
    datetime1 = datetime.datetime(2020, 1, 1)
    datetime2 = datetime.datetime(2020, 12, 31)
    #
    Calc_iVix(database, datetime1, datetime2)